package com.ad.aidai.activitys.state;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.aidai.R;
import com.ad.aidai.base.BaseActivity;
import com.ad.aidai.bean.OnActivityResultRequestCode;
import com.ad.aidai.common.utils.CheckUtil;
import com.ad.aidai.common.widgets.loading_dialog.LoadingDialog;
import com.ad.aidai.common.widgets.photoview.DragPhotoView;
import com.bumptech.glide.Glide;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 申述界面
 * <p>
 * Created by Yusxon on 17/2/6.
 */

public class StateActivity extends BaseActivity implements StateContract.View {

    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_order_content)
    TextView tvOrderContent;
    @BindView(R.id.tv_order_money)
    TextView tvOrderMoney;
    @BindView(R.id.tv_num_of_state_content_text)
    TextView tvNumOfStateContentText;
    @BindView(R.id.et_state_content)
    EditText etStateContent;
    @BindViews({R.id.iv_state_image_1, R.id.iv_state_image_2, R.id.iv_state_image_3})
    ImageView[] ivStateImages;
    @BindView(R.id.iv_state_image_add)
    ImageView ivStateImageAdd;
    @BindViews({R.id.fl_state_image_1, R.id.fl_state_image_2, R.id.fl_state_image_3})
    FrameLayout[] flStateImages;

    private StateContract.Presenter mPresenter;

    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;

    private LoadingDialog loadingDialog;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_state);
        ButterKnife.bind(this);

        etStateContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                tvNumOfStateContentText.setText(charSequence.length() + "");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {
        new StatePresenter(this, this).subscribe();

        mBasIn = new BounceTopEnter();
        mBasOut = new SlideTopExit();

        mPresenter.loadOrder();
    }

    @Override
    public void setPresenter(StateContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @OnClick({R.id.iv_back, R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                back();
                break;
            case R.id.tv_submit:
                if (CheckUtil.checkStrNull(etStateContent.getText().toString())) {
                    toast("申述内容不能为空");
                } else {
                    mPresenter.submit();
                }
                break;
        }
    }

    @OnClick({R.id.iv_state_image_1, R.id.iv_state_image_d1, R.id.iv_state_image_2, R.id.iv_state_image_d2, R.id
            .iv_state_image_3, R.id.iv_state_image_d3, R.id.iv_state_image_add})
    public void onClickImage(View view) {
        switch (view.getId()) {
            case R.id.iv_state_image_1:
                DragPhotoView.startDragPhotoActivity(this, ivStateImages[0], mPresenter.getImageUrl(0));
                break;
            case R.id.iv_state_image_d1:
                mPresenter.deleteImage(0);
                break;
            case R.id.iv_state_image_2:
                DragPhotoView.startDragPhotoActivity(this, ivStateImages[1], mPresenter.getImageUrl(1));
                break;
            case R.id.iv_state_image_d2:
                mPresenter.deleteImage(1);
                break;
            case R.id.iv_state_image_3:
                DragPhotoView.startDragPhotoActivity(this, ivStateImages[3], mPresenter.getImageUrl(3));
                break;
            case R.id.iv_state_image_d3:
                mPresenter.deleteImage(2);
                break;
            case R.id.iv_state_image_add:
                addImage();
                break;
        }
    }

    @Override
    public void showOrderType(String orderType) {
        tvOrderType.setText(orderType);
    }

    @Override
    public void showOrderTime(String orderTime) {
        tvOrderTime.setText(orderTime);
    }

    @Override
    public void showOrderStatus(String orderStatus) {
        tvOrderStatus.setText(orderStatus);
    }

    @Override
    public void showOrderContent(String orderContent) {
        tvOrderContent.setText(orderContent);
    }

    @Override
    public void showOrderMoney(String orderMoney) {
        tvOrderMoney.setText(orderMoney);
    }

    @Override
    public void showStateImage(String... urls) {
        int position = 0;
        ivStateImageAdd.setVisibility(View.VISIBLE);
        for (String url : urls) {
            flStateImages[position].setVisibility(View.GONE);
            if (!CheckUtil.checkStrNull(url)) {
                Glide.with(this)
                        .load(url)
                        .placeholder(R.mipmap.default_image)
                        .dontAnimate()
                        .into(ivStateImages[position]);
                flStateImages[position].setVisibility(View.VISIBLE);
                position++;
                if (position >= 3) {
                    ivStateImageAdd.setVisibility(View.GONE);
                    break;
                }
            }
        }
    }

    @Override
    public String getStateContent() {
        return etStateContent.getText().toString();
    }

    @Override
    public void showLoading() {
        //显示加载对话框
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("提交中...")
                .setFailedText("提交失败")
                .setSuccessText("提交成功")
                .show();
    }

    @Override
    public void closeLoading(boolean success) {
        if (loadingDialog != null) {
            if (success) {
                loadingDialog.loadSuccess();
            } else {
                loadingDialog.loadFailed();
            }
        }
    }

    /**
     * 检查是否有编辑过
     *
     * @return
     */
    private boolean checkEdit() {
        if (!tvNumOfStateContentText.getText().toString().equals("0")) {
            return true;
        }
        if (mPresenter.getImageCount() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        back();
    }

    NormalDialog dialog;

    private void back() {

        if (!checkEdit()) {
            StateActivity.this.finish();
            return;
        }

        dialog = new NormalDialog(this);
        dialog.content("申述未提交，确认离开？")
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(20)
                .btnText("确定", "取消")
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (dialog.isShowing()) {
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        StateActivity.this.finish();
                                    }
                                });
                            }
                        }).start();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == OnActivityResultRequestCode.CHOOSE_STATE_IMAGE) {
                List<ImageItem> images = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                List<String> paths = new ArrayList<>();
                for (int i = 0; i < images.size(); ++i) {
                    paths.add(images.get(i).path);
                }
                mPresenter.addImage(paths);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void addImage() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setShowCamera(true);//显示拍照按钮
        imagePicker.setSelectLimit(3 - mPresenter.getImageCount());//选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);//裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);

        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, OnActivityResultRequestCode.CHOOSE_STATE_IMAGE);
    }

    @Override
    public void exit() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (loadingDialog != null && loadingDialog.isShowing()) {

                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //申述提交完成，退出页面
                        StateActivity.this.finish();
                    }
                });
            }
        }).start();
    }
}
